<template>
     <div class="white-module module">
    <div class="title-h"><span></span>修改代表队信息</div>
    <div class="account-module">
      <div class="register">
        <div class="c">
          <el-form
            ref="ruleFormRef"
            :model="ruleForm"
            :rules="rules"
            label-width="140px"
            class="term-ruleForm"
            :size="formSize"
            status-icon
          >
            <el-form-item label="所属地区" >
              <div v-if="ruleForm.updAreaTimes>0">
                {{ruleForm.provinceName}} - {{ruleForm.cityName}}
              </div>
              <div v-else>
              <el-select style="width:220px" placeholder="请选择" v-model="ruleForm.province"  @change="changeProvince">
                <el-option
                    v-for="itemO in area.item"
                    :key="itemO.code"
                    :label="itemO.name"
                    :value="itemO.code">
                </el-option>
              </el-select>
              <el-select style="width:220px" placeholder="请选择" v-model="ruleForm.city" >
                <el-option
                    v-for="itemO in areaCity.item"
                    :key="itemO.code"
                    :label="itemO.name"
                    :value="itemO.code">
                </el-option>
              </el-select>
            </div>
            </el-form-item>
            <el-form-item label="代表队名称">
                <el-input v-model.trim="ruleForm.teamName" placeholder="请输入"/>
            </el-form-item>
            <el-form-item label="代表队负责人" >
                <el-input v-model.trim="ruleForm.realName" />
            </el-form-item>
            <el-form-item label="联系方式(手机)" >
              <el-input v-model.trim="ruleForm.phone" placeholder="请输入"/>
              <span class="btn-code" @click="queryUser">查询手机号</span>
            </el-form-item>
            <el-form-item label="性别" >
              {{ruleForm.sex?(ruleForm.sex==='1'?'男':'女'):''}}
            </el-form-item>
            <el-form-item label="证件类型" >
              {{ruleForm.idType === '1' ? '居民身份证' : ruleForm.idType === '2' ? '临时身份证' : ruleForm.idType === '3' ? '港澳居民来往内地通行证' : ruleForm.idType === '4' ? '台湾居民来往大陆通行证' : ruleForm.idType === '5' ? '护照/其他' : ''}}
            </el-form-item>

            <el-form-item label="证件号码" >
              {{baseService.hideIdCard(ruleForm.idCard)}}
            </el-form-item>
            <el-form-item label="参赛单位">
              {{ruleForm.company}}
              <span class="btn-code" v-if="ruleForm.updComTimes==0" @click="reAuthVisible=true">更新单位名称</span>
            </el-form-item>
            <el-form-item label="电子邮箱" >
              <el-input v-model.trim="ruleForm.email" placeholder="请输入"/>
            </el-form-item>

            <el-form-item>

               <div class="btns">
                  <el-button type="primary" @click="submitForm(ruleFormRef)">
                  提交
                  </el-button>
                  <el-button @click="resetForm(ruleFormRef)">取消</el-button>
               </div>
            </el-form-item>
          </el-form>
          <div class="uplods">
            <el-upload disabled
              class="avatar-uploader"
              :action="baseUrl+'/front/upload'"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
              >
                  <div class="title">一寸证件照</div>
                  <div class="image" style="width: 100px; height: 140px;">
                      <img v-if="imageUrl" :src="imageUrl" class="img" />
                      <div v-else class="upload">
                          <img src="@/assets/common/upload.png">
                          <div class="text">上传一寸照片</div>
                      </div>

                  </div>
            </el-upload>
            <el-upload
              class="avatar-uploader"
              :action="baseUrl+'/front/upload'"
              :show-file-list="false"
              :on-success="handleAvatarSuccess2"
              :before-upload="beforeAvatarUpload2"
              >
                  <div class="title">负责人授权书(单位盖章)</div>
                  <div class="image image1">
                      <img v-if="imageUrl2" :src="imageUrl2" class="img" />
                      <div v-else class="upload ">
                          <img src="@/assets/common/upload.png">
                          <div class="text">上传负责人授权书</div>
                      </div>

                  </div>
            </el-upload>
          </div>
        </div>
      </div>
    </div>
    </div>

    <!--抽签弹窗-->
    <el-dialog
        v-model="reAuthVisible" :show-close="false"
        width="400px">
      <div class="confirm-dialog">
        <el-form
            ref="reAuthFormRef"
            :model="reAuthForm"
            label-width="140px"
            class="term-ruleForm"
            :size="formSize"
            status-icon
        >
          <el-form-item label="参赛单位" >
            <el-input v-model.trim="reAuthForm.company" placeholder="请输入"/>
          </el-form-item>
          <el-form-item label="统一社会信用代码" >
            <el-input v-model.trim="reAuthForm.companyNo" placeholder="请输入"/>
          </el-form-item>
        </el-form>
        <div class="btns">
          <el-button @click="reAuthVisible = false">关闭</el-button>
          <el-button type="primary" @click="reAuthCompany()">确认</el-button>
        </div>
      </div>
    </el-dialog>
  </template>
<script lang="ts" setup>
import app from "@/constants/app";
import { reactive, ref } from "vue";
import type { FormInstance, FormRules } from "element-plus";
import type { UploadProps } from 'element-plus'
import baseService from "@/service/baseService";
import utilService from "@/utils/baseService";
import {useRouter} from "vue-router";
import {removeCache} from "@/utils/cache";
import {ElMessage, ElMessageBox} from "element-plus";

const imageUrl = ref('')
const imageUrl2 = ref('')
const formSize = ref("default");
const area = ref({code:'0',item:[]});
const areaCity = ref({code:'0',item:[]});
const ruleFormRef = ref<FormInstance>();
const baseUrl = app.api;
let router = useRouter();
const ruleForm = reactive({
  id: null,
  email: "",
  company: "",
  province: "",
  provinceName: '',
  city: "",
  cityName: '',
  companyNo: '',
  realName: '',
  sex: "",
  idType: "",
  idCard: "",
  phone: "",
  code: "",
  teamName: "",
  header: "",
  empower: "",
  oldEmpower: "",
  leaderId: null,
  oldLeaderId: null,
  creator: "",
  updAreaTimes: 0,
  updComTimes: 0,
});

const reAuthForm = reactive({
  id: null,
  companyNo: "",
  company: "",
});

const rules = reactive<FormRules>({
  email: [{ required: true, message: "请输入邮箱", trigger: "blur" }],
  company: [{ required: true, message: "请输入参赛单位", trigger: "blur" }],
  //province: [{ required: true, message: "请选择地区", trigger: "change" }],
  companyNo: [{ required: true, message: "请输入执照", trigger: "blur" }],
  realName: [{ required: true, message: "请输入领队姓名", trigger: "blur" }],
  sex: [{ required: true, message: "请选择性别", trigger: "change" }],
  idType: [{ required: true, message: "请选择证件", trigger: "change", }],
  idCard: [{ required: true, message: "请输入证件号码", trigger: "blur" }],
  phone: [{ required: true, message: "请输入手机号", trigger: "blur" }],
  code: [{ required: true, message: "请输入验证码", trigger: "blur" }],
});

const reAuthVisible = ref(false);

//省份切换
const changeProvince = (val: string) => {
  ruleForm.city = '';
  selectCity();
};

const selectCity = () => {
  if (ruleForm.province != '') {
    areaCity.value.code = ruleForm.province;
    utilService.areaList(areaCity.value);
  } else {
    areaCity.value.item = [];
  }
}

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;

  //省份城市必选
  if (ruleForm.province === '') {
    ElMessage.error("请选择省份！");
    return;
  }
  if (ruleForm.city === '') {
    ElMessage.error("请选择城市！");
    return;
  }

  // 如果领队有更改过, 则跳转到领队创建页面, 否则跳转到代表队页面
  if(ruleForm.leaderId != ruleForm.oldLeaderId){
    // 授权书必须重新上传
    if(ruleForm.empower == ruleForm.oldEmpower){
      ElMessage.error("请重新上传授权书");
      return;
    }
  }
  await formEl.validate((valid, fields) => {
    if (valid) {
      baseService
          .post("/front/spteam/update", ruleForm)
          .then((res) => {
                if (res.code === 0) {
                  ElMessage.success("修改成功, 请重新登录");
                  // 如果领队有更改过, 则跳转到领队创建页面, 否则跳转到代表队页面
                  if(ruleForm.leaderId != ruleForm.oldLeaderId){
                    //移除缓存
                    removeCache('CacheToken', true);
                    removeCache('userInfo', true);

                    //延迟1秒跳转
                    setTimeout(function(){
                      router.push('/');
                    },1000);
                  }else{
                    router.push("/team/index");
                  }
                } else {
                  ElMessage.error(res.msg);
                }
              }
          );

    } else {
      console.log("error submit!", fields);
    }
  });
};

/**
 * 查询代表队信息
 */
const getTeamInfo = () => {
  baseService
      .get("/front/spteam/1", {})
      .then((res) => {
            if (res.code === 0) {
              let info = res.data;
              if(info){
                ruleForm.id = info.team.id;
                ruleForm.company = info.team.company;
                ruleForm.province = info.team.province;
                ruleForm.provinceName = info.team.provinceName;
                ruleForm.city = info.team.city;
                ruleForm.cityName = info.team.cityName;
                ruleForm.companyNo = info.team.companyNo;
                ruleForm.sex = info.creator.sex+'';
                ruleForm.idType = info.creator.idType;
                ruleForm.idCard = info.creator.idCard;
                ruleForm.phone = info.creator.phone;
                ruleForm.email = info.creator.email;
                ruleForm.realName = info.creator.realName;
                ruleForm.teamName = info.team.teamName;
                ruleForm.header = info.creator.header;
                ruleForm.empower = info.creator.empower;
                ruleForm.oldEmpower = info.creator.empower;
                ruleForm.oldLeaderId = info.team.creator;
                ruleForm.leaderId = info.team.creator;
                ruleForm.updAreaTimes = info.team.updAreaTimes?info.team.updAreaTimes:0;
                ruleForm.updComTimes = info.team.updComTimes?info.team.updComTimes:0;
                imageUrl.value = info.creator.header;
                //imageUrl2.value = info.creator.empower;
                selectCity();
                if(info.creator.empower){
                  //判断是否包含后缀为.pdf
                  if(info.creator.empower.indexOf('.pdf') != -1) {
                    imageUrl2.value = 'http://img.fii-cc.com/fii/20230604/b2f13f0061e14463b63683f3998f055a.jpg';
                  }else {
                    imageUrl2.value = info.creator.empower;
                  }
                }
              }
            }
          }
      );

};


/**
 * 查询用户信息
 * @param formEl
 */
const queryUser = async (formEl: FormInstance | undefined) => {
  //姓名不能为空
  if (ruleForm.realName === "") {
    ElMessage.error("姓名不能为空！");
    return;
  }
  //校验手机号不能为空
  if (ruleForm.phone === "") {
    ElMessage.error("手机号不能为空！");
    return;
  }
  baseService
      .post("/front/spuser/queryUser", {
        realName: ruleForm.realName,
        phone: ruleForm.phone,
        roleId: 0
      })
      .then((res) => {
            if (res.code === 0) {
              ruleForm.idType = res.data.idType;
              ruleForm.idCard = res.data.idCard;
              ruleForm.sex  = res.data.sex+'';
              ruleForm.email = res.data.email;
              ruleForm.header = res.data.header;
              ruleForm.leaderId = res.data.id;
              imageUrl.value = res.data.header;
            } else {
              ElMessage.error(res.msg);
            }
          }
      );
};

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
  window.history.go(-1);
};


const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile
) => {
  imageUrl.value = URL.createObjectURL(uploadFile.raw!)
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (!(rawFile.type == 'image/jpeg'||rawFile.type == 'image/png'||rawFile.type == 'image/jpg')) {
    ElMessage.error('仅支持JPG/JPEG/PNG格式!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('一寸证件照不能超过2MB!')
    return false
  }
  return true
}


const handleAvatarSuccess2: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
  ruleForm.empower = response.data.src;
  imageUrl2.value = URL.createObjectURL(uploadFile.raw!)
  if(response.data.showSrc){
    imageUrl2.value = response.data.showSrc;
  }
}

const beforeAvatarUpload2: UploadProps['beforeUpload'] = (rawFile) => {
  if (!(rawFile.type == 'image/jpeg'||rawFile.type == 'image/png'||rawFile.type == 'image/jpg' || rawFile.type == 'application/pdf')) {
    ElMessage.error('仅支持JPG/JPEG/PNG/PDF格式!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 100) {
    ElMessage.error('授权书不能超过100MB!')
    return false
  }
  return true
}

/**
 * 重新认证
 */
const reAuthCompany = () => {
  //校验单位名称不能为空
  if (reAuthForm.company === "") {
    ElMessage.error("单位名称不能为空！");
    return;
  }
  //校验单位代码不能为空
  if (reAuthForm.companyNo === "") {
    ElMessage.error("单位代码不能为空！");
    return;
  }
  reAuthForm.id = ruleForm.id;
  //弹出确认框
  ElMessageBox.confirm('确定更新单位名称吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    baseService
        .post("/front/spteam/reAuthCompany", reAuthForm)
        .then((res) => {
              if (res.code === 0) {
                ElMessage.success("更新单位名称成功！");
                //关闭弹窗
                reAuthVisible.value = false;
                //刷新页面
                getTeamInfo();
              } else {
                ElMessage.error(res.msg);
              }
            }
        );
  }).catch(() => {
    ElMessage.info('取消更新单位名称');
  });
}

getTeamInfo();
utilService.areaList(area.value);

</script>
<style lang="scss" scoped>
@import "../account/account";

.title-h {
  display: flex;
  align-items: center;
  font-size: 16px;
  font-weight: $font-weight-bold;
  padding: 24px 24px 0px;


  span {
    width: 4px;
    height: 12px;
    background: #00a0e9;
    margin-right: 7px;
  }
}

.account-module .register,
.account-module {
  width: 100%;
  height: auto;
  display: block;
  background: none;

  .c .term-ruleForm {

    padding: 0px;
    margin-top: 10px;
    margin-left: 30px;

    .btn-code {
      width: 98px;
      line-height: 32px;
      background: #EFF6FF;
      border-radius: 4px;
      text-align: center;
      color: $color-primary;
      margin-left: 12px;

    }

    .btns {
      width: 100%;
      margin-left: 275px;
      margin-top: 12px;
      display: block;
    }
  }

  .c .uplods {
    top: 231px;
    display: flex;
    left: 480px;
    right: inherit;
    margin-right: 52px;

    .avatar-uploader {

      margin-right: 52px;
    }
  }
}
</style>
<style lang="scss">
.term-ruleForm {
  .el-input {
    width: 220px;
  }

  .el-form-item--default .el-form-item__label {
    font-weight: $font-weight-bold;
    color: #333;
  }
  .el-radio__inner{
          border-color:#a8abb2;
      }
  .el-button{
        width: 108px;
        height: 38px;
      }

}
</style>

